package com.bcmusic.oauth.service.impl;


import com.bcmusic.oauth.service.LoginService;
import com.bcmusic.oauth.util.AuthToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.DefaultResponseErrorHandler;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.util.Base64;
import java.util.Map;

/**
 * @ClassName : LoginServiceImpl  //类名
 * @Description :   //描述
 * @Author : YG  //作者
 * @Date: 2020-09-22 19:23  //时间
 */
@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RestTemplate restTemplate;

    @Autowired
    private LoadBalancerClient loadBalancerClient;

    @Override
    public AuthToken login(String username, String password, String clientId, String clientSecret, String grandType)throws Exception {
        //1.定义url (申请令牌的url)
        //参数 : 微服务的名称spring.appplication指定的名称
//        ServiceInstance choose = loadBalancerClient.choose("user-auth");
//        String url =choose.getUri().toString()+"/oauth/token";
        String url="http://127.0.0.1:9001/oauth/token";

        //2.定义头信息 (有client id 和client secr)
        MultiValueMap<String,String> headers = new LinkedMultiValueMap<>();
        headers.add("Authorization","Basic "+ Base64.getEncoder().encodeToString(new String(clientId+":"+clientSecret).getBytes()));
        //3. 定义请求体  有授权模式 用户的名称 和密码
        MultiValueMap<String,String> formData = new LinkedMultiValueMap<>();
        formData.add("grant_type",grandType);
        formData.add("username",username);
        //请求 携带 头 和请求体 到认证服务器
        formData.add("password",password);

        /**
         * 参数1  指定要发送的请求的url
         * 参数2  指定要发送的请求的方法 PSOT
         * 参数3 指定请求实体(包含头和请求体数据)
         */
        HttpEntity<MultiValueMap> requestentity = new HttpEntity<MultiValueMap>(formData,headers);
        System.out.println(url);

//        restTemplate.setErrorHandler(new DefaultResponseErrorHandler(){
//            @Override
//            public void handleError(ClientHttpResponse response) throws IOException {
//                System.out.println("错误了111");
//                if(response.getRawStatusCode() != 401){
//                    System.out.println("错误了");
//                    super.handleError(response);
//                }
//            }
//        });
        restTemplate.setRequestFactory(new HttpComponentsClientHttpRequestFactory());
        ResponseEntity<Map> responseEntity=null;
        try {
            responseEntity = restTemplate.exchange(url, HttpMethod.POST, requestentity, Map.class);
        }catch (HttpClientErrorException e)
        {
            e.printStackTrace();
            return null;
        }
        //5.接收到返回的响应(就是:令牌的信息)
        Map body = responseEntity.getBody();

        //封装一次.

        AuthToken authToken = new AuthToken();
        //访问令牌(jwt)
        String accessToken = (String) body.get("access_token");
        //刷新令牌(jwt)
        String refreshToken = (String) body.get("refresh_token");
        //jti，作为用户的身份标识
        String jwtToken= (String) body.get("jti");


        authToken.setJti(jwtToken);
        authToken.setAccessToken(accessToken);
        authToken.setRefreshToken(refreshToken);

        //6.返回
        return authToken;
    }


}
